#include"BlockQueue.hpp"
#include"Task.hpp"

const string str = "+-*/%";

pthread_mutex_t mutex;

void* productor(void* args)
{
  BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
  while(true)
  {
    //sleep(1);
    int x = rand() % 100;
    int y = rand() % 100;
    char op = str[rand() % str.size()];
    Task task(x,y,op);
    bq->push(task);
    pthread_mutex_lock(&mutex);//显示器也是共享资源，也需要加锁
    cout << "我是生产者，向阻塞队列发送任务 : " << task.FormatArg() << endl;
    pthread_mutex_unlock(&mutex);
  }
  return nullptr;
}

void* consumer(void* args)
{
  BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
  while(true)
  {
    //sleep(1);
    Task task;
    bq->pop(task);
    task();
    pthread_mutex_lock(&mutex);//显示器也是共享资源，也需要加锁
    cout << "我是消费者，从阻塞队列取任务 : " << task.FormatRes() << endl;
    pthread_mutex_unlock(&mutex);
  }
  return nullptr;
}

int main()
{
  BlockQueue<Task>* bq = new BlockQueue<Task>();
  
  srand(time(nullptr) ^ getpid());

  pthread_t c,p;
  pthread_create(&c,nullptr,consumer,bq);
  pthread_create(&p,nullptr,productor,bq);

  pthread_join(c,nullptr);
  pthread_join(p,nullptr);
  return 0;
}
